package com.fate.box

import android.util.Log
import com.huawei.hms.push.HmsMessageService
import io.flutter.plugin.common.MethodChannel
import android.os.Handler
import android.os.Looper

class HwHmsMessageService : HmsMessageService() {
    private val channelName = "com.example.app/get/token" // 自定义通道名称
    private val mainHandler = Handler(Looper.getMainLooper())
    private var myToken = ""
    override fun onNewToken(token: String?) {
        super.onNewToken(token)
        Log.e("HwHmsMessageService", "获取到华为的token:$token")
        // 判断token是否为空
        if (!token.isNullOrEmpty()) {
            myToken = token;
            refreshedTokenToServer(token)
        }
    }

    private fun refreshedTokenToServer(token: String) {
        mainHandler.post {
            var engine = FlutterIMApplication.getFlutterEngine()
            val channel = MethodChannel(engine.dartExecutor.binaryMessenger,channelName)
            channel.setMethodCallHandler { call, result ->
                if (call.method == "flutterGetToken") {
                    Log.i("HwHmsMessageService", "flutter需要我们准备token:$token,并发送")
                    result.success("$myToken")
                } else {
                    result.notImplemented()
                }
            }
            channel.invokeMethod("onTokenReceived",token)
            Log.i("HwHmsMessageService", "sending token to server. token:$token===$channelName")
        }

    }

}